package gui;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

import main.SerialFrame;

public class Logger {
	private static final int FLUSH_FREQUENCY_MILLIS = 5000;
	
	private static WriteThread thread;
	private static Object lock;
	private static ConcurrentLinkedQueue<String> buffer;
	private static boolean shouldFlush;
	
	static {
		buffer = new ConcurrentLinkedQueue<String>();
		lock = new Object();
		thread = new WriteThread();
		thread.start();
		shouldFlush = true;
	}
	
	public static void flush() {
		synchronized (lock) {
			shouldFlush = true;
			lock.notifyAll();
		}
	}
	
	public static void add(String s) {
		buffer.add(s);
		if (s.length() >= 1024) flush();
	}
	
	private static class WriteThread extends Thread {
		public void run() {
			while (true) {
				synchronized (lock) {
					if (!shouldFlush) {
						try {
							Thread.sleep(FLUSH_FREQUENCY_MILLIS);
						} catch (InterruptedException e) { }
					}
					shouldFlush = false;
				}
				
				if (!buffer.isEmpty()) {
					FileWriter out = null;
					try {
						out = new FileWriter(SerialFrame.LOG_PATH, true);
						String toAdd = buffer.poll();
						while (toAdd != null) {
							out.write(toAdd);
							toAdd = buffer.poll();
						}
						out.close();
					} catch (IOException e) {
						// ignore exception
					} finally {
						if (out != null) {
							try {
								out.close();
							} catch (IOException e) { }
						}
					}
				}
			}
		}
	}
}
